package code.starivan.leetcode;

/**
 * Created by Ivan on 2015/8/22.
 */

/*
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

        Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
        Output: 7 -> 0 -> 8
*/

public class N002_AddTwoNum {
    //Definition for singly-linked list.
    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null)
            return l2;

        if(l2==null)
            return l1;

        ListNode node1=l1;
        ListNode node2=l2;
        ListNode pre=null;
        ListNode head=null;
        int add=0;
        while (node1!=null&&node2!=null){
            int sum=node1.val+node2.val+add;
            add=sum/10;
            sum=sum%10;
            ListNode node=new ListNode(sum);
            if(pre==null){
                head=node;
            }else{
                pre.next=node;
            }
            pre=node;
            node1=node1.next;
            node2=node2.next;
        }

        while (add!=0){
            int sum=add;
            if(node1!=null){
                sum+=node1.val;
                node1=node1.next;
            }else if(node2!=null){
                sum+=node2.val;
                node2=node2.next;
            }

            add=sum/10;
            sum=sum%10;
            ListNode node=new ListNode(sum);
            pre.next=node;
            pre=node;
        }

        if(node1!=null){
            pre.next=node1;
        }else if(node2!=null){
            pre.next=node2;
        }

        return head;
    }
}
